package api.servlet;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.PostConstruct;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Random;

/**
 * @author xiakai
 * @create 2020-12-05 10:43
 */
@Controller
public class AnimeController {

    static ArrayList<String> nameList;
    static String address;

    static int size;

    static Random random;

    @PostConstruct
    public void init() throws IOException {

        random = new Random();
        nameList = new ArrayList<>();
        File file = new File("info.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));
        address = br.readLine();
        String line = null;
        while ((line = br.readLine()) != null) {
            nameList.add(URLEncoder.encode(line, "UTF-8").replaceAll("\\+", "%20"));
        }
        size = nameList.size();
    }

    @RequestMapping("/anime")
    @ResponseBody
    public ModelAndView hello(@RequestParam(name = "type", defaultValue = "img") String type) throws IOException {
        if (type.equals("img")) {
            return new ModelAndView("redirect:" + getRandomImg());
        }
        if (type.equals("json")) {
            return null;
        }
        return null;
    }

    public String getRandomImg() {
        return address + nameList.get(random.nextInt(size));
    }


}
